package com.itcast.googleplay.ui;

import com.itcast.googleplay.R;
import com.itcast.googleplay.utils.UIUtils;
import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;

public abstract class LoadingPage extends FrameLayout {
	public View loadingView;
	public View errorView;
	public View emptyView;
	public View successedView;
	
	public static final int STATE_NONE = 0;
	public static final int STATE_LOADING = 1;
	public static final int STATE_ERROR = 2;
	public static final int STATE_EMPTY = 3;
	public static final int STATE_SUCCESSED = 4;
	
	public int state = STATE_NONE;
	
	public LoadingPage(Context context) {
		super(context);
		initView();
	}
	private void initView() {
		//创建一个正在加载的view
		loadingView = onCreateLoadingView();
		if(loadingView!=null){
			addView(loadingView);
		}
		//创建一个请求数据失败的view
		errorView = onCreateErrorView();
		if(errorView!=null){
			addView(errorView);
		}
		//创建一个请求数据为空的view
		emptyView = onCreateEmptyView();
		if(emptyView!=null){
			addView(emptyView);
		}
		//展示界面
		showPage();
	}
	private void showPage() {
		if(loadingView!=null){
			if(state == STATE_NONE || state == STATE_LOADING){
				loadingView.setVisibility(View.VISIBLE);
			}else{
				loadingView.setVisibility(View.GONE);
			}
		}
		
		if(errorView!=null){
			errorView.setVisibility((state == STATE_ERROR)?View.VISIBLE:View.GONE);
		}
		
		if(emptyView!=null){
			emptyView.setVisibility((state == STATE_EMPTY)?View.VISIBLE:View.GONE);
		}
		
		if(state == STATE_SUCCESSED){
			removeView(successedView);
			//状态为加载成功
			successedView = onCreateSuccessView();
			addView(successedView);
		}
		if(successedView!=null){
			successedView.setVisibility((state == STATE_SUCCESSED)?View.VISIBLE:View.GONE);
		}
	}
	
	public void show(){
		if(state == STATE_NONE || state == STATE_SUCCESSED || state == STATE_ERROR || state == STATE_EMPTY){
			state = STATE_NONE;
		}
		
		if(state == STATE_NONE){
			new Thread(){
				public void run() {
					final ResultState onload = onload();
					UIUtils.runInMainThread(new Runnable() {
						@Override
						public void run() {
							state = onload.getState();
							showPage();
						}
					});
				};
			}.start();
		}
	}
	
	private View onCreateEmptyView() {
		return UIUtils.inflate(R.layout.layout_empty_view);
	}
	private View onCreateErrorView() {
		return UIUtils.inflate(R.layout.layout_error_view);
	}
	private View onCreateLoadingView() {
		return UIUtils.inflate(R.layout.layout_loading_view);
	}
	
	public abstract View onCreateSuccessView() ;
	public abstract ResultState onload();
	
	public enum ResultState{
		STATE_ERROR(2),
		STATE_EMTPY(3),
		STATE_SUCCESSED(4);
		
		private int state;
		private ResultState(int state){
			this.state = state;
		}
		public int getState(){
			return state;
		}
	}
}
